﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Web.Security;
using Cofe.Core;
using Cofe.Core.Security;
using WebMatrix.WebData;
using Cofe.Web.Utils;

namespace Cofe.Web
{
    [Export(typeof(ICofeService))]
    [ServicePriority(ServicePriorityAttribute.DefaultPriority_COFEWS)]
    public class WSUserManager : UserManager
    {
        #region Constructor


        #endregion

        #region Methods

        public static void SetRole(string userName, WebUserRole role)
        {
            SimpleRoleProvider provider = (SimpleRoleProvider)Roles.Provider;

            if (provider.GetRolesForUser(userName).Length > 0)
                provider.RemoveUsersFromRoles(new string[] { userName }, provider.GetRolesForUser(userName));
            provider.AddUsersToRoles(new string[] { userName }, new string[] { role.GetRoleString() });
        }

        public override IPrincipal GetPrincipal(IIdentity identity = null)
        {
            if (identity == null || !identity.IsAuthenticated)
                return createPrincipal(_policies.ToArray(), null, false);

            List<IPrincipalPolicy> policies = new List<IPrincipalPolicy>(_policies);
            if (identity.AuthenticationType == "Forms")
            {
                policies = new List<IPrincipalPolicy>(_policies);
                SimpleRoleProvider provider = (SimpleRoleProvider)Roles.Provider;
                var additionalRoles = provider.GetRolesForUser(identity.Name);
                if (additionalRoles.Length > 0)
                    policies.Add(new GenericPrincipalPolicy(additionalRoles, "Forms", identity.Name));
            }

            return createPrincipal(policies.ToArray(), identity, false);
        }

        #endregion

        #region Data

        #endregion

        #region Public Properties

        #endregion

    }
}
